unit common;

{$mode objfpc}{$H+}

interface

uses
  Classes,
  SysUtils,
  hadeobject,
  hadeconnectionmanager,
  hadesession;

type
  { TAddress }

  TAddress = class(THadeObject)
  private
    FEmail: string;
    FPhone: integer;
  published
    property Phone: integer read FPhone write FPhone;
    property Email: string read FEmail write FEmail;
  end;

  { TPerson }

  TPerson = class(THadeObject)
  private
    FAge: integer;
    FLName: string;
    FName: string;
    FAddress: TAddress;
    function getAddress: TAddress;
  public
    destructor Destroy; override;
  published
    property Age: integer read FAge write FAge;
    property Last_Name: string read FLName write FLName;
    property First_Name: string read FName write FName;
    property Address: TAddress read getAddress write FAddress;
  end;

  { TPersonList }

  TPersonList = class(THadeObjectList)
  protected
    function getItem(index: integer): TPerson; reintroduce;
  public
    property Items[iloop: integer]: TPerson read getItem;
  end;

var
  session: THadeSession;

implementation

uses
  hadeopfmanager,
  hademapping,
  hadebroker;

procedure init;
begin
  GHadeOPFManager.ConnectionManager.RegisterConnection('test', 'test.s3db',
    '', 'SYSDBA', 'masterkey', SQLDB_SQLite,TRUE);

  GHadeMappingManager.RegisterMapping('test',TPerson, 'person', 'OID', 'oid',
    ftInteger, 0, [ptkPK, ptkReadOnly]);

  GHadeMappingManager.RegisterMapping('test',TPerson, 'person', 'First_Name',
    'first_name', ftVarchar, 25);

  GHadeMappingManager.RegisterMapping('test',TPerson, 'person', 'Age', 'age', ftInteger, 3);

  GHadeMappingManager.RegisterMapping('test',TPerson, 'person', 'Last_Name',
    'last_name', ftVarchar, 25);

  GHadeMappingManager.RegisterMapping('test',TPerson, 'person', 'Address',
    'address', ftReference, 0, [ptkFK]);


  GHadeMappingManager.RegisterMapping('test',TAddress, 'address', 'OID', 'oid',
    ftInteger, 0, [ptkPK, ptkReadOnly]);

  GHadeMappingManager.RegisterMapping('test',TAddress, 'address', 'Phone', 'phone'
    , ftInteger, 8);

  GHadeMappingManager.RegisterMapping('test',TAddress, 'address', 'Email', 'email',
    ftVarchar, 35);

  GHadeMappingManager.RegisterObjectList('test',TPersonList, TPerson);

  GHadeOPFManager.OIDStrategy := oidAutoInc;
  { session lifetime }
  session := GHadeSessionFactory.CreateSession('test');
end;

{ TPersonList }

function TPersonList.getItem(index: integer): TPerson;
begin
  Result := TPerson(inherited getItem(index));
end;

{ TPerson }

function TPerson.getAddress: TAddress;
begin
  Result := fAddress;
end;

destructor TPerson.Destroy;
begin
  if Assigned(FAddress) then
    FreeAndNil(fAddress);
  inherited Destroy;
end;

initialization
  init;

end.

